package com.chencai.wiki;

import java.io.IOException;
import java.util.Map;

import com.chencai.wiki.database.utils.DataAccess;

public class WikiBussiness 
{

	private WikiBussiness()
	{
		
	}
	
	private String goToPage(Map<String, String> params) throws IOException
	{
		if ( !params.get("method").equals("goTo") ) {
			throw new IOException("request paramter illegal!");
		}
		
		String title = params.get("title");
		if ( title == null || title.length() == 0 ){
			throw new IOException("request paramter error: with on title property!");
		}
		
		String content = DataAccess.getDataAccess().getPage(title);
		if(content == null){
			return null;
		}
		
		String header = "<p class=\"title\">" + title + "</p>";
		return header + WikiParser.toHtml(content);
	}
	
	
	private String searchItemTitle(Map<String, String> params)
	{
		//System.out.println("searchItem!");
		String queryTitle = params.get("query").trim();
		//System.out.println(queryTitle);
		String content = DataAccess.getDataAccess().getPage( queryTitle );
		if( content == null ) {
			return "<p>can't find any related result</p><p><a href=\"#\" onclick=\"createNew(' " + queryTitle + "')\">create new item</a><p>";
		} else {
			String header = "<h1 class=\"title\">" + queryTitle + "</h1>";
			return header + WikiParser.toHtml(content);
		}
	}
	
	private String save(Map<String, String> params)
	{
		String title = params.get("title");
		String content = params.get("content");
		String author = params.get("author");
		//System.out.println("title=" + title);
		//System.out.println("content=" + content);
		//System.out.println("author=" + author);
		DataAccess.getDataAccess().insertPage(title, author, content);
		String header = "<p class=\"title\">" + title + "</p>";
		return header + WikiParser.toHtml(content);
	}
	
	private String edit(Map<String, String> params)
	{
		String title = params.get("title");
		return DataAccess.getDataAccess().getPage(title);
	}
	
	private static WikiBussiness instance = new WikiBussiness();
	
	/**
	 * the service processor interface
	 * @param params the parameters of the service
	 * @param method the mothodId
	 * @return
	 * @throws IOException
	 */
	public static String processRequest(Map<String, String> params, String method)
		throws IOException
	{
		int methodID = Integer.parseInt(method);
		
		switch (methodID) {
		case 1:
			return instance.goToPage(params); 
		case 2:
			return instance.searchItemTitle(params);
		case 3:
			return instance.save(params);
		case 4:
			return instance.edit(params);
		default:
		}
		
		return null;
	}
	
}
